package com.sskj.one.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.hjq.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.base.AppManager;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.UserInfo;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.HideUtil;
import com.sskj.one.R;
import com.sskj.one.WebActivity;
import com.sskj.one.bean.Menu;
import com.sskj.one.component.DaggerUserDataComponent;
import com.sskj.one.login.LoginActivity;
import com.sskj.one.view.TipDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author Hey
 * Create at  2019/05/21
 */
public class MineFragment extends BaseFragment<MinePresenter> {
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tv_mobile;
    @BindView(R.id.group)
    Group group;
    @BindView(R.id.constraint)
    ConstraintLayout constraint;
    @BindView(R.id.tv_user_mobile)
    TextView tvUserMobile;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_jiehui)
    TextView tvJiehui;
    @BindView(R.id.tv_gouhui)
    TextView tvGouhui;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_exit)
    TextView tvExit;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_kefu)
    TextView tv_kefu;
    @BindView(R.id.tv_jiehui_way)
    TextView tv_jiehui_way;
    @BindView(R.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @Inject
    UserViewModel userViewModel;

    private UserData userData;

    List<Menu> menuData = new ArrayList<>();
    private SlimAdapter<Menu> slimAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (scrollView != null) {
                scrollView.fling(0);
                scrollView.smoothScrollTo(0, 0);
            }
            if (mPresenter != null) {
                mPresenter.getUserInfo();
            }
        }
    }

    @Override
    public void initView() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("1", R.mipmap.head_one);
        map.put("2", R.mipmap.head_two);
        map.put("3", R.mipmap.head_three);
        map.put("4", R.mipmap.head_four);
        map.put("5", R.mipmap.head_five);
        map.put("6", R.mipmap.head_six);
        map.put("7", R.mipmap.head_seven);
        map.put("8", R.mipmap.head_eight);
        map.put("9", R.mipmap.head_nine);
        map.put("10", R.mipmap.head_ten);
        map.put("11", R.mipmap.head_eleven);
        map.put("12", R.mipmap.head_twelve);
        map.put("13", R.mipmap.head_thirteen);
        map.put("14", R.mipmap.head_fourteen);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                if (isEmpty(userData.getUpic()) || isEmpty(userData.getNickname())) {
                    group.setVisibility(View.GONE);
                    tvUserMobile.setVisibility(View.VISIBLE);
                } else {
                    group.setVisibility(View.VISIBLE);
                    tvUserMobile.setVisibility(View.GONE);
                    ImageUtil.setImage(map.get(userData.getUpic()), iv_head);
                }
                tvUserMobile.setText(HideUtil.getPhoneHide(userData.getMobile()));
                tvName.setText(userData.getNickname());
                tv_mobile.setText(HideUtil.getPhoneHide(userData.getMobile()));
                tvMoney.setText(NumberUtil.keep(userData.getUsable(), 5));
            } else {
                userData = null;
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(App.INSTANCE)
                .setLastDraw(false)
                .setFirstDraw(false)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.divide))
                .setPaintWidth((int) RudenessScreenHelper.dp2px(App.INSTANCE, 1))
                .setLeftPadding((int) RudenessScreenHelper.dp2px(App.INSTANCE, 15))
                .setRightPadding((int) RudenessScreenHelper.dp2px(App.INSTANCE, 15)));
        menuData.add(new Menu("平台公告", R.mipmap.icon_gonggao, GongGaoActivity.class));
        menuData.add(new Menu("安全中心", R.mipmap.icon_safe, SafeCenterActivity.class));
        menuData.add(new Menu("我要邀请", R.mipmap.icon_invite, InviteActivity.class));
        menuData.add(new Menu("资金明细", R.mipmap.icon_money, AssetDetailActivity.class));
        menuData.add(new Menu("新手须知", R.mipmap.icon_new_player, SafeCenterActivity.class));
        menuData.add(new Menu("关于我们", R.mipmap.icon_about, SafeCenterActivity.class));
        menuData.add(new Menu("交易查询", R.mipmap.icon_check, CheckTransactionActivity.class));
        slimAdapter = SlimAdapter.create().register(R.layout.item_mine, new SlimInjector<Menu>() {
            @Override
            public void onInject(Menu data, IViewInjector iViewInjector, List list) {
                iViewInjector.text(R.id.tv_item, data.getText())
                        .clicked(R.id.ll_item, v -> {
                            if ("新手须知".equals(data.getText())) {
                                WebActivity.start(getActivity(), "trade_rule");
                                return;
                            }
                            if ("关于我们".equals(data.getText())) {
                                WebActivity.start(getActivity(), "about_aml");
                                return;
                            }
                            startActivity(new Intent(getActivity(), data.getClz()));
                        })
                        .image(R.id.iv_item, data.getIcon());
            }
        }).attachTo(recyclerView).updateData(menuData);

        ClickUtil.click(300, tvJiehui, () -> {
            if (userData == null) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
            if (isEmpty(userData.getBank_nums()) && isEmpty(userData.getAlipay_nums())) {
                ToastUtils.show("请先添加结汇方式");
                return;
            }
            HuiActivity.start(getActivity(), Constans.JIE_HUI);
        });
        ClickUtil.click(300, tvGouhui, () -> {
            HuiActivity.start(getActivity(), Constans.GOU_HUI);
        });
        ClickUtil.click(300, tvExit, () -> {
            new TipDialog(getActivity())
                    .setContentText("您是否确定退出")
                    .setCancel(true)
                    .setListener(dialog -> {
                        LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
                        logoutProvider.logout();
                    }).show();
        });
        ClickUtil.click(300, tv_kefu, () -> {
            //WebH5Activity.start(getActivity(), "客服", BaseHttpConfig.KEFU, false);
            KeFuWebView.start(getActivity(), "客服", BaseHttpConfig.KEFU, false);
        });
        ClickUtil.click(300, constraint, () -> {
            UserInfoActivity.start(getActivity());
        });
        ClickUtil.click(300, tv_jiehui_way, () -> {
            JieHuiActivity.start(getActivity());
        });
    }


    @Override
    public void initData() {
        tvVersion.setText("当前版本号：V" + APKVersionCodeUtils.getVerName(App.INSTANCE));
        smartRefreshView.setOnRefreshListener(refreshLayout -> mPresenter.getUserInfo());
    }


    public void stopRefresh() {
        if (smartRefreshView != null && smartRefreshView.isRefreshing()) {
            smartRefreshView.finishRefresh();
        }
    }


    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void getUserInfoOK(UserInfo data) {
        if (data == null) {
            return;
        }
        userData.setMobile(data.getMobile());
        userData.setAccount(data.getAccount());
        userData.setRealname(data.getRealname());
        userData.setNickname(data.getNickname());
        userData.setIdcard(data.getIdcard());
        userData.setIs_set_tpwd(data.getIs_set_tpwd());
        userData.setUpic(data.getUpic());
        userData.setBank_username(data.getBank_username());
        userData.setBank_name(data.getBank_name());
        userData.setBank_sub_name(data.getBank_sub_name());
        userData.setBank_nums(data.getBank_nums());
        userData.setAlipay_username(data.getAlipay_username());
        userData.setAlipay_nums(data.getAlipay_nums());
        userData.setAlipay_img(data.getAlipay_img());
        userData.setUserid(data.getAsset().getUserid());
        userData.setPid(data.getAsset().getPid());
        userData.setMark(data.getAsset().getMark());
        userData.setUsable(data.getAsset().getUsable());
        userData.setFrost(data.getAsset().getFrost());
        userData.setCzprice(data.getAsset().getCzprice());
        userData.setTxprice(data.getAsset().getTxprice());
        userData.setLock_num(data.getAsset().getLock_num());
        userData.setIs_ti(data.getAsset().getIs_ti());
        userViewModel.update(userData);
    }
}
